import os
from binascii import b2a_hex
from hashlib import md5

from app.util.id_util import uuid
from eshop_django import settings

BaseDir = settings.BASE_DIR


def get_file_type(file_path):
    i = file_path.rindex('.')
    file_type = file_path[i + 1:]
    return file_type


def get_file_name(file_path):
    i = file_path.rindex(os.path.sep)
    file_name = file_path[i + 1:]
    return file_name


def get_file_path(file_path):
    i = file_path.rindex(os.path.sep)
    file_path = file_path[: i + 1]
    return file_path


def static_file_path(file_type):
    tmp_dir = BaseDir + os.path.sep + 'static' + os.path.sep + 'error_log' + os.path.sep
    if not os.path.exists(tmp_dir):
        os.mkdir(tmp_dir)
    return tmp_dir + uuid() + "." + file_type


def order_file_dir():
    file_dir = BaseDir + os.path.sep + 'static' + os.path.sep + 'order' + os.path.sep
    if not os.path.exists(file_dir):
        os.mkdir(file_dir)
    return file_dir


def order_image_dir():
    file_dir = BaseDir + os.path.sep + 'static' + os.path.sep + 'order_image' + os.path.sep
    if not os.path.exists(file_dir):
        os.mkdir(file_dir)
    return file_dir


def tmp_file_path(file_type):
    tmp_dir = BaseDir + os.path.sep + 'tmp' + os.path.sep
    if not os.path.exists(tmp_dir):
        os.mkdir(tmp_dir)
    return tmp_dir + uuid() + "." + file_type


def file_md5(file_name_or_url):
    file = None
    try:
        file_name = file_name_or_url
        index = file_name.rfind(os.path.sep, )
        if index != -1:
            file_name = file_name_or_url[index:]
        # print(file_name)
        path = __file__

        path = path[: path.find(os.path.sep + 'SettleAccounts' + os.path.sep)]
        path = path + os.path.sep + 'static' + file_name

        # print(path)
        file = open(path, 'rb')
        mm = md5()
        content = b2a_hex(file.read())
        mm.update(content)
        return mm.hexdigest()

    except BaseException as e:
        return e.__str__()
    finally:
        if file:
            file.close()

# print(file_md5('http://www.qsong.ren/1.jpg'))
# print(file_md5('http://www.qsong.ren/2.jpg'))
# print(file_md5('http://www.qsong.ren/3.jpg'))
# print(file_md5('http://www.qsong.ren/4.png'))
# 1252d3de7366a16d3fc66aa3d860c3ab
# ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 0100010000ffdb004300
